﻿using LD.Host;
using System;
using System.Text;
using System.Threading;

namespace LD
{
    public class CCDClientEx : BaseCommunication
    {
        private ManualResetEvent m_waitReceiveData = new ManualResetEvent(false);
        private object m_lock = new object();
        public CCDClientEx(TcpIpParameModel parame)
        {
            Parame = parame;
            m_Socket = new SocketHelper(parame.Ip, parame.Port);
            m_Socket.ConnectionEvent += M_Socket_ConnectionEvent;
            m_Socket.ReceiveDataEvent += M_Socket_ReceiveDataEvent;
        }
        private void M_Socket_ConnectionEvent(bool obj)
        {
            ConnectionStateEvent?.Invoke(Parame.Name, obj ? Status.成功 : Status.失败);
        }
        public TcpIpParameModel Parame { get; private set; }

        public override void Connect()
        {
            m_Socket.CreateConnect();
        }
        private void M_Socket_ReceiveDataEvent(byte[] obj)
        {
            ReceiveString = Encoding.UTF8.GetString(obj);
            m_waitReceiveData.Set();
        }
        private string ReceiveString;

        public override object Send(string content)
        {
            lock (m_lock)
            {
                ReceiveString = string.Empty;
                try
                {
                    m_waitReceiveData.Reset();

                    m_Socket.Send(content);

                    var result = m_waitReceiveData.WaitOne(5000);

                    if (!result)
                        Log4.Warr($"【{Parame.Name}】等5秒后未收到信息");
                }
                catch (Exception ex)
                {
                    Log4.Error($"【{Parame.Name}】{ex.Message}");
                }
                return ReceiveString;
            }
        }
        private SocketHelper m_Socket;
        public override void Closed()
        {
            m_Socket?.Closed();
        }
    }
}
